<template>
  <div class="course-join-manage">
    <div class="header">
      <el-button type="primary" disabled>新增</el-button>
    </div>
    <el-table :data="courseJoinStore.courseJoins" style="width: 100%">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column label="课程名称">
        <template #default="{ row }">
          {{ getCourseName(row.courseId) }}
        </template>
      </el-table-column>
      <el-table-column label="学生姓名">
        <template #default="{ row }">
          {{ getStudentName(row.studentId) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          {{ statusMap[row.status] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="showEditDialog(row)"
            :icon="Edit"
          >修改</el-button>
          <el-button
            type="warning"
            size="small"
            @click="showReviewDialog(row)"
            :icon="Check"
          >审核</el-button>
          <el-button
            type="danger"
            size="small"
            @click="courseJoinStore.deleteCourseJoin(row.id)"
            :icon="Delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改对话框 -->
    <el-dialog title="修改课程加入" v-model="editDialogVisible" width="30%">
      <el-form :model="editForm" label-width="80px" :rules="formRules" ref="editFormRef">
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="editForm.courseId" placeholder="请选择课程">
            <el-option
              v-for="course in courseStore.courses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学生" prop="studentId">
          <el-select v-model="editForm.studentId" placeholder="请选择学生">
            <el-option
              v-for="student in students"
              :key="student.id"
              :label="student.realName"
              :value="student.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="等待中" value="PENDING"></el-option>
            <el-option label="已通过" value="APPROVED"></el-option>
            <el-option label="已拒绝" value="REJECTED"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateCourseJoin" :icon="Edit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="审核课程加入" v-model="reviewDialogVisible" width="30%">
      <el-form :model="reviewForm" label-width="80px" :rules="formRules" ref="reviewFormRef">
        <el-form-item label="状态" prop="status">
          <el-select v-model="reviewForm.status" placeholder="请选择状态">
            <el-option label="已通过" value="APPROVED"></el-option>
            <el-option label="已拒绝" value="REJECTED"></el-option>
            <el-option label="等待中" value="PENDING"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="reviewCourseJoin" :icon="Check">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Edit, Check, Delete } from '@element-plus/icons-vue';
import { useCourseJoinStore } from '@/stores/api/course-join';
import { useCourseStore } from '@/stores/api/course';
import { useUserStore } from '@/stores/api/user';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const statusMap = {
  PENDING: '等待中',
  APPROVED: '已通过',
  REJECTED: '已拒绝',
};

const courseJoinStore = useCourseJoinStore();
const courseStore = useCourseStore();
const userStore = useUserStore();

const editDialogVisible = ref(false);
const reviewDialogVisible = ref(false);
const students = ref<any[]>([]);

const editForm = ref({
  id: 0,
  courseId: 0,
  studentId: 0,
  status: '',
});

const reviewForm = ref({
  id: 0,
  status: '',
});

const formRules = ref<FormRules>({
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
});

const editFormRef = ref<FormInstance>();
const reviewFormRef = ref<FormInstance>();

const getCourseName = (courseId: number) => {
  const course = courseStore.courses.find(c => c.id === courseId);
  return course ? course.title : '未知课程';
};

const getStudentName = (studentId: number) => {
  const student = students.value.find(s => s.id === studentId);
  return student ? student.realName : '未知学生';
};

const fetchStudents = async () => {
  try {
    const users = await userStore.fetchUsers();
    students.value = users.filter(user => user.role === 'STUDENT');
  } catch (error) {
    ElMessage.error('获取学生列表失败');
  }
};

const showEditDialog = (courseJoin: any) => {
  editForm.value = { ...courseJoin };
  editDialogVisible.value = true;
};

const showReviewDialog = (courseJoin: any) => {
  reviewForm.value = { id: courseJoin.id, status: courseJoin.status };
  reviewDialogVisible.value = true;
};

const updateCourseJoin = async () => {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await courseJoinStore.updateCourseJoin(editForm.value);
        editDialogVisible.value = false;
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

const reviewCourseJoin = async () => {
  if (!reviewFormRef.value) return;
  reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await courseJoinStore.reviewCourseJoin(reviewForm.value);
        reviewDialogVisible.value = false;
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

onMounted(() => {
  courseJoinStore.fetchCourseJoins();
  courseStore.fetchCourses();
  fetchStudents();
});
</script>

<style scoped>
.course-join-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}

.el-button i + span {
  margin-left: 8px;
}

.el-select {
  width: 100%;
}
</style>